package com.chenfan.ccp.autoconfigure;

import com.chenfan.ccp.plug.business.aspect.TraceIdAspect;
import com.chenfan.ccp.plug.business.send.*;
import com.chenfan.ccp.plug.business.aspect.LogRecordBeanFactoryPointcutAdvisor;
import com.chenfan.ccp.plug.business.aspect.LogRecordMethodInterceptor;
import com.chenfan.ccp.plug.business.parser.TemplateLogExpressionEvaluator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author xutong
 */
@Configuration
public class BusinessLogAutoConfigure extends AbstractAutoConfigure {
    @Bean
    public TemplateLogExpressionEvaluator templateLogExpressionEvaluator() {
        return new TemplateLogExpressionEvaluator();
    }

    @Bean
    public LogRecordBeanFactoryPointcutAdvisor logRecordBeanFactoryPointcutAdvisor(AbstractLogSender logSender, TemplateLogExpressionEvaluator templateLogExpressionEvaluator) {
        LogRecordBeanFactoryPointcutAdvisor logRecordBeanFactoryPointcutAdvisor = new LogRecordBeanFactoryPointcutAdvisor();
        logRecordBeanFactoryPointcutAdvisor.setAdvice(new LogRecordMethodInterceptor(logSender, templateLogExpressionEvaluator));
        return logRecordBeanFactoryPointcutAdvisor;
    }

    @Bean
    @ConditionalOnMissingBean(name = {"logSender", "defaultLogSender"})
    public AbstractLogSender logSender(List<AbstractLogSender> logSenders) {
        logSenders.removeIf(logSender -> logSender instanceof CompositeLogSender);
        return new CompositeLogSender(logSenders);
    }
    @Bean
    public TraceIdAspect traceIdAspect(){
        return new TraceIdAspect();
    }

    @Bean
    public AbstractLogSender rocketMqLogSender() {
        return new RocketMqLogSender();
    }

    @Bean
    public AbstractLogSender httpLogSender() {
        return new HttpLogSender();
    }

    @Bean
    public AbstractLogSender localLogSender() {
        return new LocalLogSender();
    }

    @Bean("OKHttp3")
    @ConditionalOnMissingBean
    public RestTemplate OkHttp3RestTemplate() {
        RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        return restTemplate;
    }
}
